package com.qing.demo.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @author caozhipeng
 * @date 2025/7/25
 */
@Component("nettyServer")
public class NettyServer {

    private EventLoopGroup parentGroup = new NioEventLoopGroup();
    private EventLoopGroup childGroup = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture bing(InetSocketAddress address){
        ChannelFuture channelFuture=null;
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childHandler(new MyChannelInitializer());
            channelFuture=bootstrap.bind(address).syncUninterruptibly();
            channel=channelFuture.channel();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
           if(channelFuture!=null&&channelFuture.isSuccess()){
               System.out.println("Netty服务器启动成功");
           }else{
               System.out.println("Netty服务器启动失败");
           }
        }
        return channelFuture;
    }

    public void destroy(){
        if(channel!=null){
            channel.close();
        }
        parentGroup.shutdownGracefully();
        childGroup.shutdownGracefully();
    }

    public Channel getChannel() {
        return channel;
    }
}
